<!DOCTYPE html>
<html lang="zh-CN">

<head> 
    <meta charset="UTF-8">
    <title>web workers</title> 
</head>

<body style="background-color: #eee;">

    <p>计数： <output id="result"></output></p>
    <button onclick="startWorker()">开始工作</button>
    <button onclick="stopWorker()">停止工作</button>

    <p><strong>注意：</strong> Internet Explorer 9 及更早 IE 版本浏览器不支持 Web Workers.</p>

    <script>
        var w;

        function startWorker() {
            if (typeof (Worker) !== "undefined") {
                if (typeof (w) == "undefined") {
                    w = new Worker("webworkers.js");
                }
                w.onmessage = function (event) {
                    console.log("w.onmessage",event);
                    document.getElementById("result").innerHTML = event.data;
                };
                w.onerror = function (event) {
                    console.log("w.onerror",event);
                    // document.getElementById("result").innerHTML = event.data;
                };
                w.onmessageerror = function (event) {
                    console.log("w.onmessage",event);
                    // document.getElementById("result").innerHTML = event.data;
                };
            } else {
                document.getElementById("result").innerHTML = "抱歉，你的浏览器不支持 Web Workers...";
            }
        }

        function stopWorker() {
            w.terminate();
            w = undefined;
        }
    </script>

</body>

</html>